package com.wanghangcloud.common.utils;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RSA加解密工具类
 */
public class RSAUtil {

    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        // 创建一个RSA密钥对生成器
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥长度（例如2048位）
        keyGen.initialize(512);
        // 生成密钥对
        return keyGen.generateKeyPair();
    }

    public static String encodeKeyToString(Key key) {
        // 将密钥编码为字节数组
        byte[] keyBytes = key.getEncoded();
        // 使用Base64编码将字节数组转换为字符串
        return Base64.getEncoder().encodeToString(keyBytes);
    }

    public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }

    /**
     * 将 Base64 编码的公钥字符串转换为 PublicKey 对象
     */
    public static PublicKey getPublicKeyFromString(String publicKeyBase64) throws Exception {
        // 解码 Base64 字符串为字节数组
        byte[] keyBytes = Base64.getDecoder().decode(publicKeyBase64);

        // 使用 X509EncodedKeySpec 重建公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 将 Base64 编码的私钥字符串转换为 PrivateKey 对象
     */
    public static PrivateKey getPrivateKeyFromString(String privateKeyBase64) throws Exception {
        // 解码 Base64 字符串为字节数组
        byte[] keyBytes = Base64.getDecoder().decode(privateKeyBase64);

        // 使用 PKCS8EncodedKeySpec 重建私钥
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }
}
